<template>
  <div
    class="absolute left-0 top-0 z-[100] flex flex-col w-full h-full bg-white"
    v-if="props.visible"
  >
    <!-- 弹窗表头 -->
    <div class="flex items-center border-b border-[#e6e6e6] h-14">
      <el-button text type="primary" class="!px-2 ml-3" @click="closeDialog">
        <span class="text-base">←返回</span>
      </el-button>
      <div class="text-[#d6d6d6]">|</div>
      <div class="pl-2 text-[#222] font-semibold">创建调车计划</div>
    </div>
    <!-- 内容区域 -->
    <div class="flex-1 p-5 mb-16 overflow-y-auto">
      <div class="my-5 px-4 pt-4 bg-[#fafafa]">
        <div class="flex items-center pb-4">
          <img :src="subTitle" alt="" class="w-4 h-4 mr-2" />
          <span class="mr-2 font-semibold">调车计划号:</span>
          <span class="font-semibold text-[#697dff]" v-if="shuntingPlanNo">
            {{ shuntingPlanNo }}
          </span>
          <span v-else class="text-gray-400">(选择机车后自动生成)</span>
        </div>
        <div class="flex items-center pb-4">
          <span class="mr-1 text-red-500">*</span>
          <span class="mr-2 font-semibold">选择机车:</span>
          <template v-if="!selectedLocomotive">
            <el-button type="primary" @click="onOpenLocomotiveDialog">
              <el-icon size="18" class="mr-1">
                <Plus />
              </el-icon>
              点击选择
            </el-button>
          </template>
          <template v-else>
            <div
              class="border-2 border-[#697dff] bg-[#ecedff] text-[#697dff] rounded text-sm py-1 px-3 mr-2.5"
            >
              {{ `${selectedLocomotive.locomotiveNo}, ${selectedLocomotive.currentTrack}` }}
            </div>
            <el-button type="primary" @click="onOpenLocomotiveDialog">修改</el-button>
          </template>
        </div>
        <div class="flex items-center pb-4">
          <span class="mr-1 text-red-500">*</span>
          <span class="mr-2 font-semibold">起止时间:</span>
          <div class="mr-2 w-52">
            <el-time-picker
              class="!w-full"
              is-range
              range-separator="至"
              v-model="planDuration"
              format="HH:mm"
              value-format="HH:mm"
            />
          </div>
          <span>{{ `车数: ${vehicleNumber ?? '--'}` }}</span>
        </div>
      </div>
      <el-button type="primary" class="mb-5" @click="onAddHookPlan"> 添加钩计划 </el-button>
      <el-table
        :data="hookPlanTableData"
        border
        header-row-class-name="h-14"
        header-cell-class-name="text-[#333] header-cell-custom"
        cell-class-name="h-12"
        class="w-full inner-table-custom"
        max-height="400"
      >
        <el-table-column type="index" center label="序号" fixed="left" width="60" />
        <!-- 车站 股道 类别 车数 机车方向 运行方向 作业目的 开口 备注 状态 操作 -->
        <el-table-column prop="vehicleStation" label-class-name="red-star" label="车站" width="120">
          <template #default="{ row }">
            <el-select v-model="row.vehicleStation" :disabled="row.status === 4" clearable>
              <el-option label="车站1" value="车站1" />
              <el-option label="车站2" value="车站2" />
              <el-option label="车站3" value="车站3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="track" label-class-name="red-star" label="股道">
          <template #default="{ row }">
            <el-select v-model="row.track" :disabled="row.status === 4" clearable>
              <el-option label="股道1" value="股道1" />
              <el-option label="股道2" value="股道2" />
              <el-option label="股道3" value="股道3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleType" label-class-name="red-star" label="类别" width="120">
          <template #default="{ row }">
            <el-select v-model="row.vehicleType" :disabled="row.status === 4" clearable>
              <el-option label="+" value="+" />
              <el-option label="-" value="-" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleCount" label-class-name="red-star" label="车数">
          <template #default="{ row }">
            <el-input
              :disabled="row.status === 4"
              v-model="row.vehicleCount"
              type="number"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="runDirection"
          label-class-name="red-star"
          label="运行方向"
          width="120"
        >
          <template #default="{ row }">
            <el-select v-model="row.runDirection" :disabled="row.status === 4" clearable>
              <el-option label="西出" value="西出" />
              <el-option label="东出" value="东出" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="workPurpose"
          label-class-name="red-star"
          label="作业目的"
          width="140"
        >
          <template #default="{ row }">
            <el-select v-model="row.workPurpose" :disabled="row.status === 4" clearable>
              <el-option label="作业目的1" value="作业目的1" />
              <el-option label="作业目的2" value="作业目的2" />
              <el-option label="作业目的3" value="作业目的3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="open" label="开口" />
        <el-table-column prop="remark" label="备注">
          <template #default="{ row }">
            <el-input v-model="row.remark" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <span
              class="h-5 px-2 py-0.5 text-xs text-white rounded"
              :style="{
                backgroundColor: statusDetailColorMap.find((status) => status.value === row.status)
                  ?.color
              }"
            >
              {{ statusDetailColorMap.find((item) => item.value === row.status)?.text }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <!-- 删除 上移 下移-->
            <el-button type="danger" text @click="onRemoveHookPlan(row)" class="!p-0">
              删除
            </el-button>
            <el-button type="primary" text @click="onMoveUpHookPlan(row)" class="!p-0">
              上移
            </el-button>
            <el-button type="primary" text @click="onMoveDownHookPlan(row)" class="!p-0">
              下移
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部按钮 -->
    <div
      class="absolute bottom-0 left-0 right-0 flex items-center justify-center h-16 bg-white shadow-top"
    >
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onCreateShuntingPlan">创建调车计划</el-button>
      <el-button type="primary" @click="onCreateAndTakeShuntingPlan">创建且下达调车计划</el-button>
    </div>
  </div>
  <el-dialog
    v-model="locomotiveVisible"
    modal-class="el-dialog-custom"
    title="选择机车"
    width="630"
    :close-on-click-modal="false"
    @closed="onCloseLocomotiveDialog"
  >
    <div class="p-5">
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        stripe
        highlight-current-row
        header-row-class-name="h-14"
        header-cell-class-name="text-[#333]"
        class="w-full"
        max-height="400"
      >
        <el-table-column type="index" width="55" align="center"></el-table-column>
        <!-- 机车号 当前股道 检修状态 任务情况 -->
        <el-table-column prop="locomotiveNo" label="机车号" min-width="100"></el-table-column>
        <el-table-column prop="currentTrack" label="当前股道" min-width="100"></el-table-column>
        <el-table-column prop="repairStatus" label="检修状态" min-width="100"></el-table-column>
        <el-table-column prop="taskStatus" label="任务情况">
          <template #default="{ row }">
            <span
              class="w-8 px-2 py-1 text-xs leading-none text-center text-white rounded"
              :style="{
                backgroundColor: statusColorMap[row.taskStatus].color
              }"
            >
              {{ statusColorMap[row.taskStatus].text }}
            </span>
          </template>
        </el-table-column>
        <!-- 操作，选择此机车 -->
        <el-table-column label="操作" min-width="130">
          <template #default="{ row }">
            <el-button
              type="primary"
              text
              @click="onSelectLocomotive(row)"
              v-if="row.taskStatus === 0"
            >
              <span class="mr-1">选择此机车</span>
              <el-icon v-if="row.locomotiveNo === selectedLocomotive?.locomotiveNo" size="18">
                <Select />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button @click="onCloseLocomotiveDialog">取 消</el-button>
      <el-button type="primary" @click="onSubmitLocomotiveDialog">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import subTitle from '@/assets/images/sub-title.png';
import { ElTable } from 'element-plus';

const props = defineProps<{
  visible: boolean;
}>();
const emit = defineEmits(['update:visible', 'getData']);

const tableRef = ref<InstanceType<typeof ElTable> | null>(null);

const onCancel = () => {
  closeDialog();
};
const onCreateShuntingPlan = () => {
  emit('getData', {});
  closeDialog();
};
const onCreateAndTakeShuntingPlan = () => {
  emit('getData', {});
  closeDialog();
};

const clearData = () => {
  selectedLocomotive.value = null;
  hookPlanTableData.value = [];
};

const closeDialog = () => {
  clearData();
  emit('update:visible', false);
};

// 调车计划号
const shuntingPlanNo = ref<string>('');

// 选择机车
const locomotiveVisible = ref<boolean>(false);
const onOpenLocomotiveDialog = async () => {
  await nextTick();
  const index = tableData.value.findIndex(
    (row) => row.locomotiveNo === selectedLocomotive.value?.locomotiveNo
  );
  index >= 0 && tableRef.value?.toggleRowSelection(tableData.value[index], true);
  locomotiveVisible.value = true;
};

// 起止时间
const planDuration = ref<[string, string]>(['', '']);
// 车数
const vehicleNumber = ref<number | null>(null);
// 添加钩计划
const onAddHookPlan = () => {
  hookPlanTableData.value.push({
    status: 0
  });
};
const hookPlanTableData = ref<Record<string, any>[]>([]);
// 0未下达 1待执行 2执行中 3暂停中 4已完成
const statusDetailColorMap = [
  { text: '未下达', value: 0, color: '#5da9f2' },
  { text: '待执行', value: 1, color: '#fcac0f' },
  { text: '执行中', value: 2, color: '#ff8429' },
  { text: '暂停中', value: 3, color: '#ff352d' },
  { text: '已完成', value: 4, color: '#4fc415' }
];
const onRemoveHookPlan = (row: Record<string, any>) => {
  const index = hookPlanTableData.value.findIndex((item) => item === row);
  hookPlanTableData.value.splice(index, 1);
};
const onMoveUpHookPlan = (row: Record<string, any>) => {
  const index = hookPlanTableData.value.findIndex((item) => item === row);
  if (index > 0) {
    const temp = hookPlanTableData.value[index];
    hookPlanTableData.value[index] = hookPlanTableData.value[index - 1];
    hookPlanTableData.value[index - 1] = temp;
  }
};
const onMoveDownHookPlan = (row: Record<string, any>) => {
  const index = hookPlanTableData.value.findIndex((item) => item === row);
  if (index < hookPlanTableData.value.length - 1) {
    const temp = hookPlanTableData.value[index];
    hookPlanTableData.value[index] = hookPlanTableData.value[index + 1];
    hookPlanTableData.value[index + 1] = temp;
  }
};

const tableData = ref<Record<string, any>[]>([
  {
    locomotiveNo: 'DF4D-0001',
    currentTrack: '1#股道',
    repairStatus: '正常',
    taskStatus: 0
  },
  {
    locomotiveNo: 'DF4D-0002',
    currentTrack: '2#股道',
    repairStatus: '正常',
    taskStatus: 0
  },
  {
    locomotiveNo: 'DF4D-0003',
    currentTrack: '3#股道',
    repairStatus: '正常',
    taskStatus: 1
  },
  {
    locomotiveNo: 'DF4D-0004',
    currentTrack: '4#股道',
    repairStatus: '正常',
    taskStatus: 2
  }
]);

const statusColorMap: Record<number, { text: string; color: string }> = {
  0: {
    text: '空闲',
    color: '#50c216'
  },
  1: {
    text: '占用',
    color: '#fe8822'
  },
  2: {
    text: '不可用',
    color: '#ff3333'
  }
};
const selectedLocomotive = ref<Record<string, any> | null>(null);
const onCloseLocomotiveDialog = () => {
  locomotiveVisible.value = false;
};
const onSelectLocomotive = (row: Record<string, any>) => {
  // 如果已经选择了机车，则取消选择
  if (row.locomotiveNo === selectedLocomotive.value?.locomotiveNo) {
    selectedLocomotive.value = null;
  } else {
    selectedLocomotive.value = row;
  }
};
const onSubmitLocomotiveDialog = () => {
  onCloseLocomotiveDialog();
};
</script>

<style lang="scss" scoped>
:deep(.inner-table-custom) {
  .index-column.el-table__cell {
    .cell {
      padding-left: 10px;
    }
  }
  .header-cell-custom.el-table__cell {
    .cell {
      padding-left: 10px;
    }
  }
  .el-table__cell {
    .cell {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100%;
    }
  }
}
</style>
